package com.cg.controller;

import com.cg.common.JWTUtils;
import com.cg.common.Result;
import com.cg.entity.User;
import com.cg.exception.BusinessException;
import com.cg.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.*;

import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

@CrossOrigin
@RestController
@RequestMapping("/qualityManager/user")
public class UserController {
    @Autowired
    private UserService userService;
    @PostMapping("/register")
    public Result<String> register(@RequestBody User user) {
        try {
            userService.register(user);
            return new Result<>(200, "注册成功", "注册成功");
        } catch (DataIntegrityViolationException e) {
            // 检查是否是主键冲突异常
            if (e.getMostSpecificCause() instanceof SQLException &&
                    ((SQLException) e.getMostSpecificCause()).getSQLState().equals("23000")) {
                // 抛出自定义业务异常
                throw new BusinessException("用户注册失败，用户名已存在");
            } else {
                // 抛出其他数据库异常
                throw new BusinessException("数据库操作异常：" + e.getMessage());
            }
        }
    }

    @PostMapping("/login")
    public Map<String, Object> login(@RequestBody User user) throws UnsupportedEncodingException {
        User user1 = userService.login(user.getAccount(), user.getPassword());
        System.out.println(user1);
        if(user1!=null){
          String token= JWTUtils.sign(user1.getAccount(),user1.getPassword());
            Map<String, Object> result = new HashMap<>();
            result.put("data", token);
            System.out.println("token:"+token);
            result.put("code",200);
            return result;
        }else {
            Map<String, Object> result = new HashMap<>();
            result.put("error", "error");
            return result;
        }
    }

    @GetMapping("/userInfo")
    public Result<User> getUserInfo(@RequestHeader("Authorization") String token) {
        // 从中提取用户信息
        String account = JWTUtils.getAccount(token);
        String password=JWTUtils.getPassword(token);
        User user=userService.getUserInfo(account,password);
        if (user == null) {
            return new Result<>(0, "无效的token", null);
        }

        return new Result<>(200, "获取成功", user);
    }

//
//    @RequestMapping("/user/select")
//    public   Result<User>select(@RequestBody User user){
//        User user1=userService.login(user.getAccount(), user.getPassword());
//        return new Result<>(1,"",user1);
//    }






    /*@RequestMapping("/logout")
    public Map<String, Object> logout(@RequestBody User user) throws UnsupportedEncodingException {
        JWTUtils.
    }*/

}

